package ThreadPoolExample;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Threadpool2 {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 10; i++) {
            final int tasked = i;
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println("执行工作的id是" + tasked + "是运行在线程池的线程" + Thread.currentThread().getName());
                    try {
                        //模拟任务执行时间
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println("执行工作的id" + tasked + "已经结束了");
                }
            });
        }
        //关闭线程池
        executorService.shutdown();
        try {
            if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
                executorService.shutdownNow();
            }
        } catch (InterruptedException e) {
            //当前线程在等待过程中被中断
            executorService.shutdownNow();
            //保持终端状态
            Thread.currentThread().interrupt();
        }
    }

}
